{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a8b892c8",
   "metadata": {},
   "source": [
    "Printed and electronic copies of *Modeling and Simulation in Python* are available from [No Starch Press](https://nostarch.com/modeling-and-simulation-python) and [Bookshop.org](https://bookshop.org/p/books/modeling-and-simulation-in-python-allen-b-downey/17836697?ean=9781718502161) and [Amazon](https://amzn.to/3y9UxNb)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "romantic-speech",
   "metadata": {},
   "source": [
    "# Cooling Coffee"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "higher-button",
   "metadata": {
    "tags": []
   },
   "source": [
    "*Modeling and Simulation in Python*\n",
    "\n",
    "Copyright 2021 Allen Downey\n",
    "\n",
    "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dependent-monitoring",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# download modsim.py if necessary\n",
    "\n",
    "from os.path import basename, exists\n",
    "\n",
    "def download(url):\n",
    "    filename = basename(url)\n",
    "    if not exists(filename):\n",
    "        from urllib.request import urlretrieve\n",
    "        local, _ = urlretrieve(url, filename)\n",
    "        print('Downloaded ' + local)\n",
    "    \n",
    "download('https://github.com/AllenDowney/ModSimPy/raw/master/' +\n",
    "         'modsim.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "continental-decrease",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import functions from modsim\n",
    "\n",
    "from modsim import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "moving-trademark",
   "metadata": {
    "tags": []
   },
   "source": [
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "Click here to access the notebooks: <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "capital-needle",
   "metadata": {},
   "source": [
    "So far the systems we have studied have been physical in the sense that they exist in the world, but they have not been physics in the sense of what physics classes are usually about. In the next few chapters, we'll do some physics, starting with *thermal systems*, that is, systems where the temperature of objects changes as heat transfers from one to another."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "working-senator",
   "metadata": {},
   "source": [
    "## The Coffee Cooling Problem\n",
    "\n",
    "The coffee cooling problem was discussed by Jearl Walker in \n",
    "\"The Amateur Scientist\", *Scientific American*, Volume 237, Issue 5, November 1977. Since then it has become a standard example of modeling and simulation.\n",
    "\n",
    "Here is my version of the problem:\n",
    "\n",
    "> Suppose I stop on the way to work to pick up a cup of coffee and a small container of milk. Assuming that I want the coffee to be as hot as possible when I arrive at work, should I add the milk at the coffee shop, wait until I get to work, or add the milk at some point in between?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "backed-steel",
   "metadata": {},
   "source": [
    "To help answer this question, I made a trial run with the milk and\n",
    "coffee in separate containers and took some measurements (not really):\n",
    "\n",
    "-   When served, the temperature of the coffee is 90 °C. The volume is\n",
    "    300 mL.\n",
    "\n",
    "-   The milk is at an initial temperature of 5 °C, and I take about\n",
    "    50 mL.\n",
    "\n",
    "-   The ambient temperature in my car is 22 °C.\n",
    "\n",
    "-   The coffee is served in a well insulated cup. When I arrive at work after 30 minutes, the temperature of the coffee has fallen to 70 °C.\n",
    "\n",
    "-   The milk container is not as well insulated. After 15 minutes, it\n",
    "    warms up to 20 °C, nearly the ambient temperature.\n",
    "\n",
    "To use this data and answer the question, we have to know something\n",
    "about temperature and heat, and we have to make some modeling decisions."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "retired-noise",
   "metadata": {},
   "source": [
    "## Temperature and Heat\n",
    "\n",
    "To understand how coffee cools (and milk warms), we need a model of\n",
    "temperature and heat. *Temperature* is a property of an object or a\n",
    "system; in SI units it is measured in degrees Celsius (°C). Temperature quantifies how hot or cold the object is, which is related to the average velocity of the particles that make it up.\n",
    "\n",
    "When particles in a hot object contact particles in a cold object, the\n",
    "hot object gets cooler and the cold object gets warmer as energy is\n",
    "transferred from one to the other. The transferred energy is called\n",
    "*heat*; in SI units it is measured in joules (J).\n",
    "\n",
    "Heat is related to temperature by the following equation (see\n",
    "<http://modsimpy.com/thermass>): \n",
    "\n",
    "$$Q = C~\\Delta T$$ \n",
    "\n",
    "where $Q$ is the amount of heat transferred to an object, $\\Delta T$ is the resulting change in temperature, and $C$ is the object's *thermal mass*, which is a property of the object that determines how much energy it takes to heat or cool it. In SI units, thermal mass is measured in joules per degree Celsius (J/°C)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "upper-johnson",
   "metadata": {},
   "source": [
    "For objects made primarily from one material, thermal mass can be\n",
    "computed like this: \n",
    "\n",
    "$$C = m c_p$$ \n",
    "\n",
    "where $m$ is the mass of the object and $c_p$ is the *specific heat capacity* of the material, which is the amount of thermal mass per gram (see <http://modsimpy.com/specheat>).\n",
    "\n",
    "We can use these equations to estimate the thermal mass of a cup of\n",
    "coffee. The specific heat capacity of coffee is probably close to that\n",
    "of water, which is 4.2 J/g/°C. Assuming that the density of coffee is\n",
    "close to that of water, which is 1 g/mL, the mass of 300 mL of coffee is 300 g, and the thermal mass is 1260 J/°C.\n",
    "\n",
    "So when a cup of coffee cools from 90 °C to 70 °C, the change in\n",
    "temperature, $\\Delta T$ is 20 °C, which means that 25 200 J of heat\n",
    "energy was transferred from the cup and the coffee to the surrounding environment\n",
    "(the cup holder and air in my car).\n",
    "\n",
    "To give you a sense of how much energy that is, if you were able to\n",
    "harness all of that heat to do work (which you cannot), you could\n",
    "use it to lift a cup of coffee from sea level to 8571 m, just shy of the height of Mount Everest, 8848 m."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "closed-vegetable",
   "metadata": {},
   "source": [
    "## Heat Transfer\n",
    "\n",
    "In a situation like the coffee cooling problem, there are three ways\n",
    "heat transfers from one object to another (see <http://modsimpy.com/transfer>):\n",
    "\n",
    "-   Conduction: When objects at different temperatures come into\n",
    "    contact, the faster-moving particles of the higher-temperature\n",
    "    object transfer kinetic energy to the slower-moving particles of the lower-temperature object.\n",
    "\n",
    "-   Convection: When particles in a gas or liquid flow from place to\n",
    "    place, they carry heat energy with them. Fluid flows can be caused\n",
    "    by external action, like stirring, or by internal differences in\n",
    "    temperature. For example, you might have heard that hot air rises,\n",
    "    which is a form of \"natural convection\".\n",
    "\n",
    "-   Radiation: As the particles in an object move due to thermal energy,\n",
    "    they emit electromagnetic radiation. The energy carried by this\n",
    "    radiation depends on the object's temperature and surface properties\n",
    "    (see <http://modsimpy.com/thermrad>)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "valuable-shark",
   "metadata": {},
   "source": [
    "For objects like coffee in a car, the effect of radiation is much\n",
    "smaller than the effects of conduction and convection, so we will ignore it.\n",
    "\n",
    "Convection can be a complex topic, since it often depends on details of fluid flow in three dimensions. But for this problem we will be able to get away with a simple model called \"Newton's law of cooling\"."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "freelance-target",
   "metadata": {},
   "source": [
    "## Newton's Law of Cooling\n",
    "\n",
    "*Newton's law of cooling* asserts that the temperature rate of change for an object is proportional to the difference in temperature between the object and the surrounding environment:\n",
    "\n",
    "$$\\frac{dT}{dt} = -r (T - T_{env})$$ \n",
    "\n",
    "where $t$ is time, $T$ is the temperature of the object, $T_{env}$ is the temperature of the environment, and $r$ is a constant that characterizes how quickly heat is transferred between the object and the environment."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "corrected-attachment",
   "metadata": {},
   "source": [
    "Newton's so-called \"law \" is really a model: it is a good approximation in some conditions and less good in others.\n",
    "\n",
    "For example, if the primary mechanism of heat transfer is conduction,\n",
    "Newton's law is \"true\", which is to say that $r$ is constant over a\n",
    "wide range of temperatures. And sometimes we can estimate $r$ based on\n",
    "the material properties and shape of the object.\n",
    "\n",
    "When convection contributes a non-negligible fraction of heat transfer, $r$ depends on temperature, but Newton's law is often accurate enough, at least over a narrow range of temperatures. In this case $r$ usually has to be estimated experimentally, since it depends on details of surface shape, air flow, evaporation, etc.\n",
    "\n",
    "When radiation makes up a substantial part of heat transfer, Newton's\n",
    "law is not a good model at all. This is the case for objects in space or in a vacuum, and for objects at high temperatures (more than a few\n",
    "hundred degrees Celsius, say).\n",
    "\n",
    "However, for a situation like the coffee cooling problem, we expect Newton's model to be quite good.\n",
    "\n",
    "With that, we have just one more modeling decision to make: whether to treat the coffee and the cup as separate objects or a single object. If the cup is made of paper, it has less mass than the coffee, and the specific heat capacity of paper is lower, too. In that case, it would be reasonable to treat the cup and coffee as a single object. For a cup with substantial thermal mass, like a ceramic mug, we might consider a model that computes the temperature of coffee and cup separately."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "selective-video",
   "metadata": {},
   "source": [
    "## Implementing Newtonian Cooling\n",
    "\n",
    "To get started, we'll focus on the coffee. Then, as an exercise, you can simulate the milk. In the next chapter, we'll put them together, literally.\n",
    "\n",
    "Here's a function that takes the parameters of the system and makes a `System` object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "incredible-greeting",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def make_system(T_init, volume, r, t_end):\n",
    "    return System(T_init=T_init,\n",
    "                  T_final=T_init,\n",
    "                  volume=volume,\n",
    "                  r=r,\n",
    "                  t_end=t_end,\n",
    "                  T_env=22,\n",
    "                  t_0=0,\n",
    "                  dt=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "gross-appeal",
   "metadata": {},
   "source": [
    "In addition to the parameters, `make_system` sets the temperature of the environment, `T_env`, the initial time stamp, `t_0`, and the time step, `dt`, which we will use to simulate the cooling process.\n",
    "Here's a `System` object that represents the coffee."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "fuzzy-support",
   "metadata": {},
   "outputs": [],
   "source": [
    "coffee = make_system(T_init=90, volume=300, r=0.01, t_end=30)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "rental-pearl",
   "metadata": {},
   "source": [
    "The values of `T_init`, `volume`, and `t_end` come from the statement of the problem.\n",
    "I chose the value of `r` arbitrarily for now; we will see how to estimate it soon.\n",
    "\n",
    "Strictly speaking, Newton's law is a differential equation, but over a short period of time we can approximate it with a difference equation:\n",
    "\n",
    "$$\\Delta T = -r (T - T_{env}) dt$$ \n",
    "\n",
    "where $dt$ is the time step and $\\Delta T$ is the change in temperature during that time step.\n",
    "\n",
    "Note: I use $\\Delta T$ to denote a change in temperature over time, but in the context of heat transfer, you might also see $\\Delta T$ used to denote the difference in temperature between an object and its\n",
    "environment, $T - T_{env}$. To minimize confusion, I avoid this second\n",
    "use.\n",
    "\n",
    "The following function takes the current time `t`, the current temperature, `T`, and a `System` object, and computes the change in temperature during a time step:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "tight-baptist",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def change_func(t, T, system):\n",
    "    r, T_env, dt = system.r, system.T_env, system.dt    \n",
    "    return -r * (T - T_env) * dt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "flexible-crest",
   "metadata": {},
   "source": [
    "We can test it with the initial temperature of the coffee, like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fiscal-artwork",
   "metadata": {},
   "outputs": [],
   "source": [
    "change_func(0, coffee.T_init, coffee)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "sporting-morocco",
   "metadata": {},
   "source": [
    "With `dt=1` minute, the temperature drops by about 0.7 °C, at least for this value of `r`.\n",
    "\n",
    "Now here's a version of `run_simulation` that simulates a series of time steps from `t_0` to `t_end`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "cardiac-independence",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def run_simulation(system, change_func):\n",
    "    t_array = linrange(system.t_0, system.t_end, system.dt)\n",
    "    n = len(t_array)\n",
    "    \n",
    "    series = TimeSeries(index=t_array)\n",
    "    series.iloc[0] = system.T_init\n",
    "    \n",
    "    for i in range(n-1):\n",
    "        t = t_array[i]\n",
    "        T = series.iloc[i]\n",
    "        series.iloc[i+1] = T + change_func(t, T, system)\n",
    "    \n",
    "    system.T_final = series.iloc[-1]\n",
    "    return series"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "together-adapter",
   "metadata": {},
   "source": [
    "There are two things here that are different from previous versions of `run_simulation`.\n",
    "\n",
    "First, we use  `linrange` to make an array of values from `t_0` to `t_end` with time step `dt`.\n",
    "`linrange` is similar to `linspace`; they both take a start value and an end value and return an array of equally spaced values.\n",
    "The difference is the third argument: `linspace` takes an integer that indicates the number of points in the range; `linrange` takes a step size that indicates the interval between values.\n",
    "When we make the `TimeSeries`, we use the keyword argument `index` to indicate that the index of the `TimeSeries` is the array of time stamps, `t_array`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fantastic-object",
   "metadata": {},
   "source": [
    "Second, this version of `run_simulation` uses `iloc` rather than `loc` to specify the rows in the `TimeSeries`.\n",
    "Here's the difference: \n",
    "\n",
    "* With `loc`, the label in brackets can be any kind of value, with any start, end, and time step.  For example, in the world population model, the labels are years starting in 1960 and ending in 2016.\n",
    "\n",
    "* With `iloc`, the label in brackets is always an integer starting at 0.  So we can always get the first element with `iloc[0]` and the last element with `iloc[-1]`, regardless of what the labels are.\n",
    "\n",
    "In this version of `run_simulation`, the loop variable is an integer, `i`, that goes from `0` to `n-1`, including `0` but not including `n-1`.\n",
    "So the first time through the loop, `i` is `0` and the value we add to the `TimeSeries` has index 1.\n",
    "The last time through the loop, `i` is `n-2` and the value we add has index `n-1`.\n",
    "\n",
    "We can run the simulation like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "numerous-metabolism",
   "metadata": {},
   "outputs": [],
   "source": [
    "results = run_simulation(coffee, change_func)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "earned-primary",
   "metadata": {},
   "source": [
    "The result is a `TimeSeries` with one row per time step. \n",
    "Here are the first few rows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "infectious-carolina",
   "metadata": {},
   "outputs": [],
   "source": [
    "show(results.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "color-olive",
   "metadata": {},
   "source": [
    "And the last few rows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "accompanied-melbourne",
   "metadata": {},
   "outputs": [],
   "source": [
    "show(results.tail())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "formal-headset",
   "metadata": {},
   "source": [
    "With `t_0=0`, `t_end=30`, and `dt=1`, the time stamps go from `0.0` to `30.0`.\n",
    "\n",
    "Here's what the `TimeSeries` looks like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "important-constitution",
   "metadata": {},
   "outputs": [],
   "source": [
    "results.plot(label='coffee')\n",
    "\n",
    "decorate(xlabel='Time (min)',\n",
    "         ylabel='Temperature (C)',\n",
    "         title='Coffee Cooling')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "absent-arkansas",
   "metadata": {},
   "source": [
    "The temperature after 30 minutes is 72.3 °C, which is a little higher than the measurement we're trying to match, which is 70 °C. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "absolute-desire",
   "metadata": {},
   "outputs": [],
   "source": [
    "coffee.T_final"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "light-carpet",
   "metadata": {},
   "source": [
    "To find the value of `r` where the final temperature is precisely 70 °C, we could proceed by trial and error, but it is more efficient to use a root-finding algorithm."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "funny-weekly",
   "metadata": {},
   "source": [
    "## Finding Roots\n",
    "\n",
    "The ModSim library provides a function called `root_scalar` that finds the roots of non-linear equations. As an example, suppose you want to find the roots of the polynomial \n",
    "\n",
    "$$f(x) = (x - 1)(x - 2)(x - 3)$$ \n",
    "\n",
    "A *root* is a value of $x$ that makes $f(x)=0$. Because of the way I wrote this polynomial, we can see that if $x=1$, the first factor is 0; if $x=2$, the second factor is 0; and if $x=3$, the third factor is 0, so those are the roots.\n",
    "\n",
    "I'll use this example to demonstrate `root_scalar`. First, we have to\n",
    "write a function that evaluates $f$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "small-shark",
   "metadata": {},
   "outputs": [],
   "source": [
    "def func(x):\n",
    "    return (x-1) * (x-2) * (x-3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cleared-cylinder",
   "metadata": {},
   "source": [
    "Now we call `root_scalar` like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "defensive-content",
   "metadata": {},
   "outputs": [],
   "source": [
    "res = root_scalar(func, bracket=[1.5, 2.5])\n",
    "res"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adult-management",
   "metadata": {},
   "source": [
    "The first argument is the function whose roots we want. The second\n",
    "argument is an interval that contains or *brackets* a root. The result is an object that contains several variables, including the Boolean value `converged`, which is `True` if the  search converged successfully on a root, and `root`, which is the root that was found."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "behind-perth",
   "metadata": {},
   "outputs": [],
   "source": [
    "res.root"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "disturbed-shade",
   "metadata": {},
   "source": [
    "If we provide a different interval, we find a different root."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "following-sentence",
   "metadata": {},
   "outputs": [],
   "source": [
    "res = root_scalar(func, bracket=[2.5, 3.5])\n",
    "res.root"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eligible-updating",
   "metadata": {},
   "source": [
    "If the interval doesn't contain a root, you'll get a `ValueError` and a message like `f(a) and f(b) must have different signs`.\n",
    "\n",
    "Now we can use `root_scalar` to estimate `r`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "commercial-correlation",
   "metadata": {},
   "source": [
    "## Estimating r\n",
    "\n",
    "What we want is the value of `r` that yields a final temperature of\n",
    "70 °C. To use `root_scalar`, we need a function that takes `r` as a parameter and returns the difference between the final temperature and the goal:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "genetic-compound",
   "metadata": {},
   "outputs": [],
   "source": [
    "def error_func(r, system):\n",
    "    system.r = r\n",
    "    results = run_simulation(system, change_func)\n",
    "    return system.T_final - 70"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "happy-bridal",
   "metadata": {},
   "source": [
    "This is called an *error function* because it returns the\n",
    "difference between what we got and what we wanted, that is, the error.\n",
    "With the right value of `r`, the error is 0.\n",
    "\n",
    "We can test `error_func` like this, using the initial guess `r=0.01`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "french-financing",
   "metadata": {},
   "outputs": [],
   "source": [
    "coffee = make_system(T_init=90, volume=300, r=0.01, t_end=30)\n",
    "error_func(0.01, coffee)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "statutory-activation",
   "metadata": {},
   "source": [
    "The result is an error of 2.3 °C, which means the final temperature with `r=0.01` is too high."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "excellent-fellow",
   "metadata": {},
   "outputs": [],
   "source": [
    "error_func(0.02, coffee)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "unlimited-living",
   "metadata": {},
   "source": [
    "With `r=0.02`, the error is  about -11°C, which means that the final temperature is too low. So we know that the correct value must be in between.\n",
    "\n",
    "Now we can call `root_scalar` like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "french-decline",
   "metadata": {},
   "outputs": [],
   "source": [
    "res = root_scalar(error_func, coffee, bracket=[0.01, 0.02])\n",
    "res"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "tamil-absorption",
   "metadata": {},
   "source": [
    "The first argument is the error function.\n",
    "The second argument is the `System` object, which `root_scalar` passes as an argument to `error_func`.\n",
    "The third argument is an interval that brackets the root.\n",
    "\n",
    "Here's the root we found."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "afraid-ordering",
   "metadata": {},
   "outputs": [],
   "source": [
    "r_coffee = res.root\n",
    "r_coffee"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "partial-definition",
   "metadata": {},
   "source": [
    "In this example, `r_coffee` turns out to be about `0.0115`, in units of min$^{-1}$ (inverse minutes).\n",
    "We can confirm that this value is correct by setting `r` to the root we found and running the simulation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "derived-annual",
   "metadata": {},
   "outputs": [],
   "source": [
    "coffee.r = res.root\n",
    "run_simulation(coffee, change_func)\n",
    "coffee.T_final"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "prerequisite-conditioning",
   "metadata": {},
   "source": [
    "The final temperature is very close to 70 °C."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "outer-powder",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "This chapter presents the basics of heat, temperature, and Newton's law of cooling, which is a model that is accurate when most heat transfer is by conduction and convection, not radiation.\n",
    "\n",
    "To simulate a hot cup of coffee, we wrote Newton's law as a difference equation, then wrote a version of `run_simulation` that implements it. Then we used `root_scalar` to find the value of `r` that matches the measurement from my hypothetical experiment.\n",
    "\n",
    "All that is the first step toward solving the coffee cooling problem I posed at the beginning of the chapter. As an exercise, you'll do the next step, which is simulating the milk. In the next chapter, we'll model the mixing process and finish off the problem."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "smart-yeast",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "You can access the notebooks at <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "scientific-attachment",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    "Simulate the temperature of 50 mL of milk with a starting temperature of 5 °C, in a vessel with `r=0.1`, for 15 minutes, and plot the results. Use `make_system` to make a `System` object that represents the milk, and use `run_simulation` to simulate it.\n",
    "By trial and error, find a value for `r` that makes the final temperature close to 20 °C."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "committed-angel",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "military-military",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "logical-acoustic",
   "metadata": {},
   "source": [
    "### Exercise 2\n",
    "\n",
    "Write an error function that simulates the temperature of the milk and returns the difference between the final temperature and 20 °C.  Use it to estimate the value of `r` for the milk."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "agreed-excuse",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "defined-nudist",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "loose-rehabilitation",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "alert-emerald",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
